package org.projecteboot.compent.mybatis.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.projecteboot.coreall.exception.EbootException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author LuoQiang
 * @date 2019/7/18 20:47
 **/
@Slf4j
public class CodeGenerationUtils {
    public static void main(String[] args) {
        String javaP = "src" + File.separator + "main" + File.separator + "java";
        String resourceP = "src" + File.separator + "main" + File.separator + "resources";
        ResourceBundle rb = ResourceBundle.getBundle("mybatis-plus");
        String parent = "org.projecteboot.reptile.common";
        String outputDir = "G:\\workspace2018\\eboot\\eboot-reptile\\eboot-reptile-common";
        String url = rb.getString("url");
        String author = rb.getString("author");
        String username = rb.getString("username");
        String password = rb.getString("password");
        String[] tables = {"reptile_page", "reptile_page_extract", "reptile_page_record", "reptile_page_rule", "reptile_rule",
                "reptile_text", "reptile_client", "reptile_client_page_rule"};
        tables = new String[]{"reptile_log"};
        new CodeGenerationUtils().generatorCode(new String[]{}, tables, "", javaP, resourceP, parent, outputDir, author, url, username, password, true);
    }

    public static boolean generatorCode(String[] prefixs, String[] tableNames, String moduleName, String javaP, String xmlP, String packageInfo, String outputDir,
                                        String author, String url, String username, String password, boolean extFlag) {
        if (tableNames == null || tableNames.length < 1) {
            throw new EbootException("mybatis代码生成异常，表名不能为空");
        }
        try {
            AutoGenerator mpg = new AutoGenerator();
            // 全局配置
            GlobalConfig gc = new GlobalConfig()
                    .setOutputDir(outputDir)
                    .setXmlName("%sMapper")
                    .setMapperName("%sMapper")
                    .setServiceName("%sService")
                    .setServiceImplName("%sServiceImpl")
                    .setControllerName("%sController")
                    .setAuthor(author)
                    .setBaseResultMap(true)
                    .setBaseColumnList(true)
                    .setActiveRecord(false)
                    //是否开启二级缓存
                    .setEnableCache(false)
                    //文件存在是否覆盖
                    .setFileOverride(true)
                    .setOpen(false);
            mpg.setGlobalConfig(gc);
            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setDbType(DbType.MYSQL);
            dsc.setDriverName("com.mysql.jdbc.Driver");
            dsc.setUrl(url);
            dsc.setUsername(username);
            dsc.setPassword(password);
            mpg.setDataSource(dsc);
            // 策略配置
            StrategyConfig strategy = new StrategyConfig()
                    // 此处可以修改为您的表前缀
                    .setTablePrefix(prefixs)
                    // 表名生成策略
                    .setNaming(NamingStrategy.underline_to_camel)
                    // 需要生成的表
                    .setInclude(tableNames)
                    //lombok支持
                    .setEntityLombokModel(true)
                    .setRestControllerStyle(true)
                    .setSuperServiceClass(null)
                    .setSuperServiceImplClass(null)
                    .setSuperMapperClass(null)
                    .setLogicDeleteFieldName("del_flag");
            mpg.setStrategy(strategy);
            // 包配置
            PackageConfig pc = new PackageConfig()
                    .setParent(packageInfo)
                    .setController("controller")
                    .setModuleName(moduleName);
            mpg.setPackageInfo(pc);
            mpg.setCfg(
                    // 注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
                    new InjectionConfig() {
                        @Override
                        public void initMap() {
                            Map<String, Object> map = new HashMap<>();
                            this.setMap(map);
                        }
                    }.setFileOutConfigList(new ArrayList<FileOutConfig>() {{
                        add(new FileOutConfig(
                                "/templates/entity.java.vm") {
                            // 自定义输出文件目录
                            @Override
                            public String outputFile(TableInfo tableInfo) {
                                String path = outputDir + File.separator + javaP + File.separator + packageInfo +
                                        File.separator + pc.getModuleName() + File.separator + pc.getEntity() + File.separator;
                                return path.replaceAll("\\.", "/") + tableInfo.getEntityName() + ".java";
                            }
                        });
                        add(new FileOutConfig(
                                "/templates/mapper.java.vm") {
                            // 自定义输出文件目录
                            @Override
                            public String outputFile(TableInfo tableInfo) {
                                String path = outputDir + File.separator + javaP + File.separator + packageInfo +
                                        File.separator + pc.getModuleName() + File.separator + pc.getMapper() + File.separator;
                                return path.replaceAll("\\.", "/") + tableInfo.getMapperName() + ".java";
                            }
                        });
                        add(new FileOutConfig(
                                "/templates/service.java.vm") {
                            // 自定义输出文件目录
                            @Override
                            public String outputFile(TableInfo tableInfo) {
                                String path = outputDir + File.separator + javaP + File.separator + packageInfo +
                                        File.separator + pc.getModuleName() + File.separator + pc.getService() + File.separator;
                                return path.replaceAll("\\.", "/") + tableInfo.getServiceName() + ".java";
                            }
                        });
                        add(new FileOutConfig(
                                "/templates/serviceImpl.java.vm") {
                            // 自定义输出文件目录
                            @Override
                            public String outputFile(TableInfo tableInfo) {
                                String path = outputDir + File.separator + javaP + File.separator + packageInfo +
                                        File.separator + pc.getModuleName() + File.separator + pc.getServiceImpl() + File.separator;
                                return path.replaceAll("\\.", "/") + tableInfo.getServiceImplName() + ".java";
                            }
                        });
                        add(new FileOutConfig(
                                "/templates/controller.java.vm") {
                            // 自定义输出文件目录
                            @Override
                            public String outputFile(TableInfo tableInfo) {
                                String path = outputDir + File.separator + javaP + File.separator + packageInfo +
                                        File.separator + pc.getModuleName() + File.separator + pc.getController() + File.separator;
                                return path.replaceAll("\\.", "/") + tableInfo.getControllerName() + ".java";
                            }
                        });
                        add(new FileOutConfig(
                                "/templates/mapper.xml.vm") {
                            // 自定义输出文件目录
                            @Override
                            public String outputFile(TableInfo tableInfo) {
                                String path = outputDir + File.separator + xmlP + File.separator + pc.getXml() + File.separator + pc.getModuleName() +
                                        File.separator;
                                return path.replaceAll("\\.", "/") + tableInfo.getMapperName() + ".xml";
                            }
                        });
                        if (extFlag) {
                            add(new FileOutConfig(
                                    "/templates/extMapper.xml.vm") {
                                // 自定义输出文件目录
                                @Override
                                public String outputFile(TableInfo tableInfo) {
                                    String path = outputDir + File.separator + xmlP + File.separator + pc.getXml() + File.separator + pc.getModuleName() +
                                            File.separator;
                                    return path.replaceAll("\\.", "/") + "Ext" + tableInfo.getMapperName() + ".xml";
                                }
                            });
                            add(new FileOutConfig(
                                    "/templates/extMapper.java.vm") {
                                // 自定义输出文件目录
                                @Override
                                public String outputFile(TableInfo tableInfo) {
                                    String path = outputDir + File.separator + javaP + File.separator + packageInfo +
                                            File.separator + pc.getModuleName() + File.separator + pc.getMapper() + File.separator;
                                    return path.replaceAll("\\.", "/") + "Ext" + tableInfo.getMapperName() + ".java";
                                }
                            });
                        }
                    }})
            ).setTemplate(new TemplateConfig().setXml(null).setController(null).setEntity(null).setMapper(null).setService(null).setServiceImpl(null));
            // 执行生成
            mpg.execute();
            //移动文件

        } catch (Exception e) {
            log.error("mybatisPlus代码生成异常", e);
            return false;
        }
        return true;
    }

    private void moveTotherFolders(String from, String to) {
        String startPath = from;
        String endPath = to;
        try {
            File startFile = new File(startPath);
            File tmpFile = new File(endPath);//获取文件夹路径
            if (!tmpFile.exists()) {//判断文件夹是否创建，没有创建则创建新文件夹
                tmpFile.mkdirs();
            }
            if (startFile.renameTo(startFile)) {
                System.out.println("File is moved successful!");
                log.info("文件移动成功！from:{},to:{}", from, to);
            } else {
                System.out.println("File is failed to move!");
                log.info("文件移动失败！文件名：《{}》 起始路径：{}", from, startPath);
            }
        } catch (Exception e) {
            log.info("文件移动异常！文件名：《{}》 起始路径：{}", from, startPath);

        }
    }
}
